import {GetUserConfig, GetCountdownTimer, SetCountdownTimer, HumanTime, ShowTime, RepeatTime, SetThemeMode, GetBrowserType, IsDebugMode, GetVersion} from "./common.js";

/**
 * @since 2024-09-23 定时函数，倒计时信息
 */
let interval = null,  timer = null;

$(document).ready(function(){
  /**
   * @since 2024-09-19 主函数
   */
  Main();
});

/**
 * @title 主函数
 * @author start2004
 * @since 2024-09-20
 *
 * @return {null}
 */
async function Main(){
  /**
   * @since 2024-10-30 按钮名称
   */
  $("#repeat-time").html(chrome.i18n.getMessage("repeat"));
  $("#toggle-time").html(chrome.i18n.getMessage("pause"));
  $("#cancel-time").html(chrome.i18n.getMessage("cancel"));

  /**
   * @since 2024-09-20 渲染时间按钮
   */
  RenderTimeBtn();

  /**
   * @since 2024-09-23 开始倒计时
   */
  RunCountdownTime();

  /**
   * @since 2025-08-26 图标点击跳转到插件商店页面
   */
  $("#icon").on("click", function (){
    let language = chrome.i18n.getMessage("language");
    let url = "https://chromewebstore.google.com/detail/countdown-timer/iiojlhdhlafeffmainahbnaejlkclifl?hl="+ language;
    if(GetBrowserType() === "edge") url = "https://microsoftedge.microsoft.com/addons/detail/countdown-timer/afiffkieamhkelejioljpnhpedmkffbl?hl="+ language.replace("_", "-");
    window.open(url);
  });

  /**
   * @since 2025-08-26 开发者版本，添加测试版本信息
   */
  let debug = await IsDebugMode();
  if(debug){
    let version = await GetVersion();
    $("#version").html(version);

    $("#version").on("click", function (){
      window.open("../pages/popup.html");
    });
  } else {}
}

/**
 * @title 渲染时间按钮
 * @author start2004
 * @since 2024-09-20
 *
 * @return {null}
 */
async function RenderTimeBtn(){
  /**
   * @since 2024-09-20 获取配置信息
   */
  let config = await GetUserConfig();
  SetThemeMode(config);

  /**
   * @since 2024-09-20 时间按钮btn
   */
  let htmlArray = new Array();
  for(const time of config["checked-time"]){
    let html = '<span class="time-btn btn-light" data-time="'+ time +'">+'+ HumanTime(time) +'</span>'
    htmlArray.push(html);
  }
  htmlArray.push('<span class="time-btn btn-light" data-time="option.html">'+ chrome.i18n.getMessage("set") +'</span>');
  $("#set-time").html(htmlArray.join("&nbsp;"));

  /**
   * @since 2024-09-20 增加时间按钮的监听
   */
  $(".time-btn").click(function() {
    AddCountdownTime($(this).data("time"));
  });

  /**
   * @since 2024-09-30 监听重复按钮
   */
  $("#repeat-time").click(function() {
    /**
     * @since 2024-09-30 重新开始
     */
    timer.lastendtime = parseInt(new Date().getTime() / 1000);
    timer = RepeatTime(timer);

    /**
     * @since 2024-09-30 通知background
     * @since 2024-09-30 新的倒计时
     * @since 2024-09-30 Toggle按钮，防止暂停状态
     */
    SendMessageBackground();
    RunCountdownTime();
    ShowPause();
  });

  /**
   * @since 2024-09-20 监听暂停按钮
   * @since 2024-09-30 倒计时时间，也支持点击暂停
   */
  $("#toggle-time").click(function() {
    ToggleTime();
  });
  $("#show-time").click(function (){
    ToggleTime();
  });

  /**
   * @since 2024-09-23 监听取消按钮
   */
  $("#cancel-time").click(function() {
    CancelTime();
  });
}

/**
 * @title 开始倒计时
 * @author start2004
 * @since 2024-09-20
 *
 * @param {number|string} addTime 倒计时时间，单位秒|跳转链接
 * @return {null}
 */
async function AddCountdownTime(addTime){
  /**
   * @since 2024-09-26 非数字，跳转链接，自定义时间选项
   */
  if(isNaN(addTime)){
    window.location.href = addTime;
    return ;
  } else {}

  /**
   * @since 2024-09-20 获取倒计时信息
   */
  if(timer === null){
    timer = await GetCountdownTimer();
  } else {}

  /**
   * @since 2024-09-20 当前时间
   * @since 2024-09-20 暂停，增加未执行的时间
   * @since 2024-09-24 运行中，在结束时间上加
   */
  let now = parseInt(new Date().getTime() / 1000);
  if(timer.pause){
    /**
     * @since 2024-09-26 暂停情况下，当前时间 + 上次未执行时间 + 新增倒计时
     * @since 2024-09-26 增加，总倒计时
     */
    timer.endtime = now + timer.pausetime + addTime;
    timer.countdowntime = timer.countdowntime + addTime;
  } else {
    /**
     * @since 2024-09-26 上次倒计时未结束
     * @since 2024-09-26 增加，总倒计时
     */
    if(now <= timer.endtime){
      timer.endtime = timer.endtime + addTime;
      timer.countdowntime = timer.countdowntime + addTime;
    } else {
      /**
       * @since 2024-09-26 上次倒计时结束，新的倒计时开始
       * @since 2024-09-26 重置总倒计时
       */
      timer.endtime = now + addTime;
      timer.countdowntime = addTime;
    }
  }
  timer.done = false;
  timer.pause = false;
  timer.pausetime = 0;

  /**
   * @since 2024-09-20 保存倒计时信息
   */
  SetCountdownTimer(timer);

  /**
   * @since 2024-09-23 显示倒计时信息
   */
  RunCountdownTime();

  /**
   * @since 2024-09-23 通知background
   */
  SendMessageBackground();
}

/**
 * @title 执行倒计时
 * @author start2004
 * @since 2024-09-20
 *
 * @return {null}
 */
async function RunCountdownTime(){
  /**
   * @since 2024-09-20 倒计时信息
   */
  if(timer === null){
    timer = await GetCountdownTimer();

    /**
     * @since 2024-09-27 出现background未执行，这里通知一下background
     */
    SendMessageBackground();
  } else {}

  /**
   * @since 2024-09-20 当前时间
   * @since 2024-09-20 倒计时暂停
   * @since 2024-09-24 倒计时结束，清理Timer
   */
  const now = parseInt(new Date().getTime() / 1000);
  if(timer.pause) {
    if(timer.pausetime > 0){
      ShowCountdowntime();
      $("#show-time").html(ShowTime(timer.pausetime));
      ShowContinue();
      ClearInterval();
    } else {
      ClearTimer();
    }
    return ;
  } else {}

  if(timer.done){
    ClearTimer();
    return ;
  } else {}

  /**
   * @since 2024-09-20 计算还剩多少倒计时间
   */
  const diff = timer.endtime - now;
  if(diff > 0){
    const showTime = ShowTime(diff);
    $("#show-time").html(showTime);
    ShowCountdowntime();

    /**
     * @since 2024-09-23 启动定时任务
     */
    if(interval === null){
      interval = setInterval(RunCountdownTime, 1000);
    } else {}
  } else {
    /**
     * @since 2024-09-23 任务结束
     * @since 2024-09-23 background会更新storage
     */
    ClearTimer();
  }
}

/**
 * @title 取消倒计时
 * @author start2004
 * @since 2024-09-23
 *
 * @return {null}
 */
function CancelTime(){
  /**
   * @since 2024-09-24 清理倒计时信息
   */
  timer.lastendtime = parseInt(new Date().getTime() / 1000);
  ClearTimer();

  /**
   * @since 2024-09-23 通知background
   */
  SendMessageBackground();
}

/**
 * @title 清理倒计时信息
 * @author start2004
 * @since 2024-09-24
 *
 * @return {null}
 */
function ClearTimer(){
  /**
   * @since 2024-09-24 清理倒计时
   */
  timer.pause = false;
  timer.done = true;
  timer.endtime = 0;
  timer.pausetime = 0;

  /**
   * @since 2024-09-24 倒计时改成00:00:00
   * @since 2024-09-24 改成暂停按钮
   */
  ShowCountdowntime();
  $("#show-time").html("00:00:00");
  ShowPause();

  /**
   * @since 2024-09-23 清除定时任务
   */
  if(interval !== null) {
    clearInterval(interval);
    interval = null;
  } else {}
}

/**
 * @title 通知background
 * @author start2004
 * @since 2024-09-24
 *
 * @return {null}
 */
function SendMessageBackground(){
  /**
   * @since 2024-09-23 通知background
   */
  chrome.runtime.sendMessage({action: "update-timer", data: timer});
}

/**
 * @title 暂停/继续倒计时任务
 * @author start2004
 * @since 2024-09-24
 *
 * @return {null}
 */
function ToggleTime(){
  /**
   * @since 2024-09-24 继续任务
   */
  if(timer.pause){
    /**
     * @since 2024-09-26 显示暂停
     */
    ShowPause();

    /**
     * @since 2024-09-24 当前时间
     * @since 2024-09-24 增加未执行的时间
     */
    const now = parseInt(new Date().getTime() / 1000);
    timer.endtime = now + timer.pausetime;

    /**
     * @since 2024-09-24 更新Timer
     */
    timer.pause = false;
    timer.pausetime = 0;
    SetCountdownTimer(timer);

    /**
     * @since 2024-09-24 启动任务
     * @since 2024-09-24 通知background
     */
    RunCountdownTime();
    SendMessageBackground();
  } else {
    /**
     * @since 2024-09-24 暂停任务
     *
     * @since 2024-09-24 当前时间
     * @since 2024-09-24 检查还有多少时间未执行
     */
    const now = parseInt(new Date().getTime() / 1000);
    const diff = timer.endtime - now;

    /**
     * @since 2024-09-24 没有时间需要继续
     */
    if(diff < 0) return ;

    /**
     * @since 2024-09-24 更新Timer
     */
    timer.pause = true;
    timer.pausetime = diff;
    SetCountdownTimer(timer);

    /**
     * @since 2024-09-24 更新显示按钮
     * @since 2024-09-24 通知background
     * @since 2024-09-24 清除定时任务
     */
    ShowContinue();
    SendMessageBackground();
    ClearInterval();
  }
}

/**
 * @title 清理定时任务
 * @author start2004
 * @since 2024-09-24
 *
 * @return {null}
 */
function ClearInterval(){
  if(interval !== null) {
    clearInterval(interval);
    interval = null;
  } else {}
}

/**
 * @title 上次设置倒计时
 * @author start2004
 * @since 2024-09-26
 *
 * @return {null}
 */
function ShowCountdowntime(){
  if(timer.countdowntime > 0){
    $("#countdown-time").html(ShowTime(timer.countdowntime));
  } else {
    $("#countdown-time").html("");
  }

  /**
   * @since 2024-11-01 上次倒计时结束的时间
   */
  if(timer.lastendtime > 0){
    let lastendtime = chrome.i18n.getMessage("last_end_time");

    /**
     * @since 2024-11-01 时间
     */
    let date = new Date(timer.lastendtime*1000);

    let year = date.getFullYear();
    let month = date.getMonth()+1;
    const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    let enmonth = months[month-1];

    if(month < 10) month = "0"+ month;
    let day = date.getDate();
    let enday = day;
    if(day < 10) day = "0"+ day;

    let hours = date.getHours();
    let ampm = (hours >= 12) ? "PM" : "AM";
    let enhours = hours % 12;
    if(enhours == 0) enhours = 12;

    if(hours < 10) hours = "0"+ hours;
    let minutes = date.getMinutes();
    if(minutes < 10) minutes = "0"+ minutes;

    /**
     * @since 2024-11-01 中文时间，2024-11-01 22:22
     * @since 2024-11-01 英文时间，1:15 AM · Oct 31, 2024，X推特目前用的
     */
    if(chrome.i18n.getMessage("language") == "en"){
      lastendtime += enhours + ":" + minutes + " " + ampm + " · " + enmonth + " " + enday + ", " + year;
    } else {
      lastendtime += year + "-" + month + "-" + day + " " + hours + ":" + minutes;
    }
    $("#countdown-time").attr("title", lastendtime);
  } else {
    $("#countdown-time").attr("title", "");
  }
}

/**
 * @title 显示暂停
 * @author start2004
 * @since 2024-09-26
 *
 * @return {null}
 */
function ShowPause(){
  $("#toggle-time").html(chrome.i18n.getMessage("pause"));
  $("#toggle-time").attr('class', 'btn-light');
}

/**
 * @title 显示继续
 * @author start2004
 * @since 2024-09-26
 *
 * @return {null}
 */
function ShowContinue(){
  $("#toggle-time").html(chrome.i18n.getMessage("continue"));
  $("#toggle-time").attr('class', 'btn-pause');
}